# -*- coding: utf-8 -*-

import zipfile, pdb, os
from pprint import pprint
from conf.sysConfig import config
import xml.dom.minidom as xml
from xml.dom.minidom import parse, parseString
import xml.etree.ElementTree as ET

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
DuanDir = os.path.join(tmpDir, "Duan")


def unzip_Sim_XmlFile(path, fileName):
    if not zipfile.is_zipfile(path):
        return 0
    zip_file = zipfile.ZipFile(path)
    list_name = zip_file.namelist()
    matcher = [fileName]
    matching = [i for i in list_name if any(xs in i for xs in matcher)]
    if len(matching) == 0:
        return 0
    # pdb.set_trace()
    mkDirs(DuanDir)
    # xml_file = zip_file.extract(os.path.join(DuanDir, fileName))
    xml_file = zip_file.extract(matching[0], DuanDir)
    # xml_file = zip_file.extract(matching[0])
    # xml_file = read(xml_file)
    # pprint(xml_file)
    # read_xml(xml_file)
    # print(type(xml_file))
    # read_xml_1(xml_file)
    duanInfo = read_xml_gb(xml_file)
    # pdb.set_trace()
    zip_file.close()
    os.remove(xml_file)
    return duanInfo


def read_xml_gb(file):
    with open(file, "r", encoding="gb2312") as f:
        data = f.read()
        f.close()
    root = parseString(data)
    SegName = root.getElementsByTagName("SegName")
    # print(root.childNodes)
    duan = {}
    for nodelist in SegName:
        # print("TYPE:" + nodelist.getElementsByTagName('TYPE')[0].childNodes[0].nodeValue.strip())
        # print("NAME:" + nodelist.getElementsByTagName('NAME')[0].childNodes[0].nodeValue.strip())
        # print("PREFIX:" + nodelist.getElementsByTagName('PREFIX')[0].childNodes[0].nodeValue.strip())
        # print("PRODUCER:" + nodelist.getElementsByTagName('PRODUCER')[0].childNodes[0].nodeValue.strip())
        # print("DESCRIPT:" + nodelist.getElementsByTagName('DESCRIPT')[0].childNodes[0].nodeValue.strip())
        # print("ISP3SEG:" + nodelist.getElementsByTagName('ISP3SEG')[0].childNodes[0].nodeValue.strip())
        try:
            duan["KEYWORDS"] = nodelist.getElementsByTagName('KEYWORDS')[0].childNodes[0].nodeValue.strip()
        except:
            duan["KEYWORDS"] = ""
        try:
            duan["TYPE"] = nodelist.getElementsByTagName('TYPE')[0].childNodes[0].nodeValue.strip()
        except:
            duan["TYPE"] = ""
        try:
            duan["NAME"] = nodelist.getElementsByTagName('NAME')[0].childNodes[0].nodeValue.strip()
        except:
            duan["NAME"] = ""
        try:
            duan["PREFIX"] = nodelist.getElementsByTagName('PREFIX')[0].childNodes[0].nodeValue.strip()
        except:
            duan["PREFIX"] = ""
        try:
            duan["PRODUCER"] = nodelist.getElementsByTagName('PRODUCER')[0].childNodes[0].nodeValue.strip()
        except:
            duan["PRODUCER"] = ""
        try:
            duan["DESCRIPT"] = nodelist.getElementsByTagName('DESCRIPT')[0].childNodes[0].nodeValue.strip()
        except:
            duan["DESCRIPT"] = ""
        try:
            duan["ISP3SEG"] = nodelist.getElementsByTagName('ISP3SEG')[0].childNodes[0].nodeValue.strip()
        except:
            duan["ISP3SEG"] = ""
    SegVersion = root.getElementsByTagName("SegVersion")
    for nodelist in SegVersion:
        # print("VERSION:" + nodelist.getElementsByTagName('VERSION')[0].childNodes[0].nodeValue.strip())
        try:
            duan["VERSION"] = nodelist.getElementsByTagName('VERSION')[0].childNodes[0].nodeValue.strip()
        except:
            duan["VERSION"] = ""
    Category = root.getElementsByTagName("Category")
    for nodelist in Category:
        # print("APPTYPE:" + nodelist.getElementsByTagName('APPTYPE')[0].childNodes[0].nodeValue.strip())
        try:
            duan["APPTYPE"] = nodelist.getElementsByTagName('APPTYPE')[0].childNodes[0].nodeValue.strip()
        except:
            duan["APPTYPE"] = ""
    HardWare = root.getElementsByTagName("HardWare")
    for nodelist in HardWare:
        try:
            # print("CPU:" + nodelist.getElementsByTagName('CPU')[0].childNodes[0].nodeValue.strip())
            duan["CPU"] = nodelist.getElementsByTagName('CPU')[0].childNodes[0].nodeValue.strip()
        except:
            duan["CPU"] = ""
    HostRequires = root.getElementsByTagName("OPTIONAL")
    duan["HostRequires"] = []
    for nodelist in HostRequires:
        hoRequire = {}
        try:
            hoRequire["SEGPREFIX"] = nodelist.getElementsByTagName('SEGPREFIX')[0].childNodes[0].nodeValue.strip()
        except:
            hoRequire["SEGPREFIX"] = ""
        try:
            hoRequire["SEGNAME"] = nodelist.getElementsByTagName('SEGNAME')[0].childNodes[0].nodeValue.strip()
        except:
            hoRequire["SEGNAME"] = ""
        try:
            hoRequire["SEGVERSION"] = nodelist.getElementsByTagName('SEGVERSION')[0].childNodes[0].nodeValue.strip()
        except:
            hoRequire["SEGVERSION"] = ""
        duan["HostRequires"].append(hoRequire)

    # pprint(duan)
    # pdb.set_trace()
    return duan


def read_xml(file):
    # dom = xml.dom.minidom.parse(file)
    #     # ET.parse(file)
    dom = xml.dom.minidom.parse(file)
    root = dom.documentElement
    pprint(len(root.getElementsByTagName("SegName")))
    subElementObj = root.getElementsByTagName("SegName")
    print(subElementObj[0].getAttribute("TYPE"))

    pprint(root.nodeName)
    pprint(root.nodeValue)
    pprint(root.nodeType)
    pprint(root.ELEMENT_NODE)
    # with open(file, "r", encoding="gb2312") as f:
    #     data = f.read()
    #     pprint(data)
    #     f.close()
    # ET.fromstring(data)


def read_xml_1(path):
    try:
        tree = ET.parse(path)
        print("tree type:", type(tree))
        root = tree.getroot()
    except Exception as e:
        print(e)
        print("parse xml fail")

    print("root type:", type(root))
    print(root.tag, "----", root.attrib)

    for child in root:
        # print("遍历root的下一层", child.tag, "----", child.attrib)
        for cchild in child:
            print("遍历childt的下一层", cchild.tag, "----", cchild.attrib)

    print(root[0].text)
    # print(root[1][1][0].text)

    print(20 * "*")


def mkDirs(path):
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        pass
    return path


def read(path):
    dara_file = open(path, 'r')
    apath = "./1.xml"
    new_dara_file = open(apath, "w", encoding='utf-8')
    new_dara_file.truncate()

    for line in dara_file:
        line = line.encode('gb2312', 'ignore').decode('gb2312', 'ignore').replace('gb2312', 'utf-8')
        new_dara_file.write(line + '\n')

    dara_file.close()
    new_dara_file.close()

    return apath


if __name__ == '__main__':
    # unzip_Sim_XmlFile("/data/software/file/47015960-WGDLHD_JR0001zip.zip", 'SegInfo.xml')
    unzip_Sim_XmlFile(r"E:\1214\TESTFB(0.0.0.1).zip", 'SegInfo.xml')
